package com.omega.framework.common.validate.template;

import com.omega.framework.common.exception.ServiceException;
import com.omega.framework.common.model.BaseResponseCode;
import com.omega.framework.common.validate.annotation.Regex;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则校验
 *
 * @author Lv.
 * @date 2023/8/18 17:10
 */
@Component
public class RegexInvoke implements DataTypeValidate {
    @Override
    public void validateInvoke(Field field, Object object) throws IllegalAccessException {
        Regex regex = field.getAnnotation(Regex.class);
        if (regex != null && regex.enable()) {
            field.setAccessible(true);
            Object value = field.get(object);
            if (value == null) {
                if (StringUtils.isNotBlank(regex.rexMessage())) {
                    throw new ServiceException(BaseResponseCode.ONLY_THROW_MSG, regex.rexMessage());
                }
                throw new ServiceException(BaseResponseCode.ONLY_THROW_MSG, field.getName() + "正则匹配不正确");
            } else {
                if (!StringUtils.isEmpty(regex.rexRule()) && !StringUtils.isEmpty(regex.rexMessage())) {
                    Pattern pattern = Pattern.compile(regex.rexRule());
                    Matcher matcher = pattern.matcher(value.toString());
                    boolean result = matcher.matches();
                    if (!result) {
                        if (StringUtils.isNotBlank(regex.rexMessage())) {
                            throw new ServiceException(BaseResponseCode.ONLY_THROW_MSG, regex.rexMessage());
                        }
                        throw new ServiceException(BaseResponseCode.ONLY_THROW_MSG, field.getName() + "正则匹配不正确");
                    }
                }

            }
        }
    }
}
